package com.xuecheng.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;

public class AuthInfoInterceptor implements HandlerInterceptor {
    //进去controller方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1、获取请求头中的payload
        String payload = request.getHeader("payload");
        if (StringUtils.isEmpty(payload)) {
            return true;
        }
        //2、转化编码
        String json = URLDecoder.decode(payload, "UTF-8");
        //3、转化成pageinfo对象
        AuthInfo info = JSON.parseObject(json, AuthInfo.class);
        //4、存入ThreadLocal
        AuthInfoHolder.setAuthInfo(info);
        return true;//向后执行controller方法
    }
    //在响应结束之前
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
